package com.ruoyi.algorithm.controller;

import com.ruoyi.algorithm.entity.TableStruct;
import com.ruoyi.algorithm.service.TableStructService;
import com.ruoyi.algorithm.service.impl.UserTableStructServiceImpl;
import com.ruoyi.algorithm.util.ClazzUtils;
import com.beihu.sightplus.common.authorization.entity.User;
import com.beihu.sightplus.common.authorization.service.UserAuthorization;
import com.beihu.sightplus.common.response.ErrorMsgType;
import com.beihu.sightplus.common.response.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * @author ：yanfa-03
 * @date ：Created in 2021/7/12/9:59
 * @description ：表结构控制器
 * @version: 1.0
 */
@RestController
@RequestMapping("tableStruct")
@Api(tags = {"表结构控制"})
@Slf4j
public class TableStructController {

    @Autowired
    private TableStructService tableStructService;

    @Autowired
    private UserTableStructServiceImpl userTableStructService;

    @GetMapping("getTableStructs")
    @ApiOperation("获取表结构用户关联信息")
    @ApiResponse(code = 200, message = "成功", response = TableStruct.class)
    public ResultData<?> getTableStructs() {
        User userAuthorization = UserAuthorization.getUserAuthorization();
        Long userId = userAuthorization.getId();
        List<TableStruct> tableField = tableStructService.getTableField(userId, "operator");
        return ResultData.success(tableField);
    }


    @PutMapping("addTableStructs")
    @ApiOperation("新增表结构信息")
    public ResultData<?> addTableStructs() {
        List<String> classNames = ClazzUtils.getClazzName("com.ruoyi.algorithm.model",false);
        if (getClazz(classNames)) return ResultData.error(ErrorMsgType.Fail);
        List<String> classNames2 = ClazzUtils.getClazzName("com.ruoyi.algorithm.entity",false);
        if (getClazz(classNames2)) return ResultData.error(ErrorMsgType.Fail);
        return ResultData.success();
    }

    private boolean getClazz(List<String> classNames) {
        for (String singleClassName : classNames) {
            try {
                Class<?> aClass = Class.forName(singleClassName);
                tableStructService.addTableStructs(aClass);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return true;
            }
        }
        return false;
    }


}
